import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/category/CatetoryModel.dart';
import 'package:projectfluttershengyihuatong/category/catetory_controller.dart';
import 'package:projectfluttershengyihuatong/tool/extension_int.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'categoryCell.dart';
class CategoryPage extends StatefulWidget {
  const CategoryPage({super.key});

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  void initState() {
    // TODO: implement initState
    CatetoryController.request();
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    streamController.close();
    super.dispose();
  }

  late StreamController<CatetoryModel> streamController =
  StreamController<CatetoryModel>.broadcast();
  late StreamController<CatetoryModel> rightStreamController =
  StreamController<CatetoryModel>.broadcast();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(44),
        child: AppBar(
          backgroundColor: color01CAA8,
          leading: IconButton(
            color: Colors.white,
            onPressed: () {
              Get.back();
            },
            icon: Image.asset(
              assetImage("ico_back"),
              width: 15.adapt(),
              height: 15.adapt(),
            ),
          ),
          title: Text(
            "选择分类",
            style: TextStyle(
              color: Colors.white,
              fontSize: 17.adapt(),
            ),
          ),
        ),
      ),
      body: Container(
        color: Colors.white,
        child: GetBuilder<CatetoryController>(
          id: CatetoryController.categoryList,
          builder: (controller) {
            printLog("数据请求完成之后，刷新页面", StackTrace.current);

            if (controller.dataArr.isEmpty) {
              return const Center(
                child: Text("没有数据"),
              );
            } else {
              return HaveDataWidget(
                dataArr: controller.dataArr,
                streamController: streamController,
                rightStream: rightStreamController,
                defaultModel: controller.leiModel,
              );
            }
          },
        ),
      ),
    );
  }
}

class HaveDataWidget extends StatelessWidget {
  const HaveDataWidget({
    super.key,
    required this.dataArr,
    required this.streamController,
    required this.rightStream,
    required this.defaultModel,
  });
  final CatetoryModel? defaultModel;

  final List<CatetoryModel> dataArr;
  final StreamController<CatetoryModel> streamController;
  final StreamController<CatetoryModel> rightStream;

  @override
  Widget build(BuildContext context) {
    printLog("HaveDataWidget build", StackTrace.current);

    return Row(
      children: [
        Expanded(
          flex: 1,
          child: LeftListView(
            dataArr: dataArr,
            streamController: streamController,
          ),
        ),
        Expanded(
            child: RightListView(
              streamController: streamController,
              rightStream: rightStream,
              defaultModel: defaultModel,
            )),
      ],
    );
  }
}

class RightListView extends StatelessWidget {
  RightListView({
    super.key,
    required this.streamController,
    required this.rightStream,
    required this.defaultModel,
  });

  StreamController<CatetoryModel> streamController;
  final StreamController<CatetoryModel> rightStream;
  final CatetoryModel? defaultModel;

  @override
  Widget build(BuildContext context) {
    printLog("RightListView build", StackTrace.current);

    return StreamBuilder(
        stream: streamController.stream.distinct(),
        initialData: defaultModel,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final arr = snapshot.data?.children ?? [];
            return ListView.builder(
              itemBuilder: (context, index) {
                final model = arr[index];
                return RightListCell(key: ValueKey(arr[index].pid ?? 0),
                  model: model, rightStream: rightStream,callback: (){
                    CatetoryController.getInstance().saveLeiModel().then((value){
                      Get.back();
                      CatetoryController.getInstance().update([CatetoryController.leiCategory]);
                    }).onError((error, stackTrace){

                    });

                  },);
              },
              itemCount: arr.length,
            );
          }

          return Container();
        });
  }
}


class RightListCell extends StatelessWidget {
  RightListCell({super.key, required this.model, required this.rightStream, required this.callback});

  CatetoryModel model;
  final StreamController<CatetoryModel> rightStream;
  final VoidCallback callback;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        rightStream.add(model);
        CatetoryController.getInstance().leiModel = model;

        callback();
      },
      child: Container(
        padding: const EdgeInsets.only(top: 12, bottom: 12),
        child: Center(
          child: StreamBuilder(
            stream: rightStream.stream,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                if (identical(snapshot.data, model)) {
                  model.isSelected = true;
                } else {
                  model.isSelected = false;
                }
              }



              return Text(
                model.title ?? "",
                style: TextStyle(
                    fontSize: 16,
                    color: model.isSelected ? primaryColor : color33),
              );
            },
          ),
        ),
      ),
    );
  }
}





class LeftListView extends StatefulWidget {

  LeftListView(
      {super.key, required this.dataArr, required this.streamController});
  final List<CatetoryModel> dataArr;
  StreamController<CatetoryModel> streamController;

  @override
  State<LeftListView> createState() => _LeftListViewState();
}

class _LeftListViewState extends State<LeftListView> {
  @override
  void initState() {
    // TODO: implement initState

    Future.delayed(Duration(seconds: 2)).then((value){
      if (CatetoryController.getInstance().menModel != null) {
        widget.streamController.add(CatetoryController.getInstance().menModel!);

      }
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    printLog("LeftListView build", StackTrace.current);

    return Container(
      color: 0xf9f9f9.toColor(),
      child: ListView.builder(
        itemBuilder: (context, index) {
          var model = widget.dataArr[index];
          return CategoryCell(
            model: model,
            streamController: widget.streamController,
          );
        },
        itemCount: widget.dataArr.length,
      ),
    );
  }
}





